<?php


namespace support\command\workerman\process;

use app\common\gateway\data\GroupSender;
use app\common\gateway\data\JsonData;
use GatewayWorker\Lib\Gateway;
use Workerman\Connection\TcpConnection;
use Workerman\Lib\Timer;
/**
 * 服务器信息
 * @package support\command\workerman\process
 */
class CommonTask
{
    public function onWorkerStart($worker) {
        $this->vmstat($worker);
        $this->onlineCount();
    }

    public function onWorkerStop($worker) {
        @shell_exec('killall vmstat');
        @pclose($worker->process_handle);
    }

    protected function vmstat($worker) {
        // 把进程句柄存储起来，在进程关闭的时候关闭句柄
        $worker->process_handle = popen('vmstat 1', 'r');
        if($worker->process_handle)
        {
            $process_connection = new TcpConnection($worker->process_handle);
            $sender = new GroupSender('vmstat');
            $dataer = new JsonData('vmstat');
            $process_connection->onMessage = function($process_connection, $data) use($sender, $dataer) {
                $dataer->setData($data);
                // 发送给这个组的所有人员
                $sender->send($dataer);
            };
        } else {
            echo "vmstat 1 fail\n";
        }
    }

    protected function onlineCount() {
        $sender = new GroupSender('onlineCount');
        Timer::add(3, function() use ($sender){
            $data = new JsonData('onlineCount', [
                'users' => \GatewayWorker\Lib\Gateway::getAllUidCount(),
                'clients' => \GatewayWorker\Lib\Gateway::getAllClientCount()
            ]);
            $sender->send($data);
        });
    }

}
